package top.lushi78778.iot.mqtt.web.api.v1;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.onsmqtt20200420.models.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.lushi78778.iot.mqtt.configurer.MqttConfigurer;
import top.lushi78778.iot.mqtt.core.MqttClient;
import top.lushi78778.iot.mqtt.core.Result;
import top.lushi78778.iot.mqtt.core.ResultGenerator;

/**
 * @ClassName Token
 * @Description Token应用服务器接口
 * @Author lushi
 * @Date 2021/7/18 16:45
 */
@RestController
@RequestMapping("/api/token")
public class Token {

    /**
     * 调用QueryToken校验Token的有效性
     *
     * @param Token 您需查询的Token
     * @return RequestId 公共参数 TokenStatus	取值说明如下：true：该Token有效。false：该Token无效。
     * @throws Exception 异常
     */
    @ApiOperation(value = "校验 Token 的有效性")
    @RequestMapping(value = "/query",method = {RequestMethod.POST})
    public Result<Object> QueryToken(@ApiParam(value = "您需查询的Token",required = true)@RequestParam String Token) throws Exception {
        MqttConfigurer mqttConfigurer = new MqttConfigurer();
        com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
        QueryTokenRequest queryTokenRequest = new QueryTokenRequest()
                .setToken(Token)
                .setInstanceId(mqttConfigurer.getInstanceid());
        try {
            QueryTokenResponse response = client.queryToken(queryTokenRequest);
            JSONObject json = new JSONObject(response.toMap());
            String data = String.valueOf(json.getJSONObject("body"));
            return ResultGenerator.genSuccessResult(data);
        }catch (Exception exception){
            return ResultGenerator.genFailResult(exception.getMessage());
        }
    }

    /**
     * 调用ApplyToken创建临时访问Token
     *
     * @param Actions Token的权限类型 R：只有读权限。W：只有写权限。R,W：同时拥有读和写的权限，R和W之间需要用逗号（,）隔开。
     * @param ExpireTime Token有效期的毫秒时间戳。允许设置的失效最小间隔是60秒，最长为30天。如果输入的取值超过30天，申请接口不会报错，但实际生效时间为30天。
     * @return RequestId 公共参数 Token 服务端返回的Token值
     * @throws Exception 异常
     */
    @ApiOperation(value = "创建临时访问 Token")
    @RequestMapping(value = "/apply",method = {RequestMethod.POST})
    public Result<Object> ApplyToken(@ApiParam(value = "Token的权限类型 R,W：同时拥有读和写的权限，R和W之间需要用逗号（,）隔开",required = true) @RequestParam String Actions,
                                     @ApiParam(value = "Token有效期的毫秒时间戳。允许设置的失效最小是60秒，最长为30天",required = true) @RequestParam Long ExpireTime) throws Exception {
        if(ExpireTime<60000L){
            return ResultGenerator.genFailResult("允许设置的失效最小间隔是60秒");
        }
        MqttConfigurer mqttConfigurer = new MqttConfigurer();
        com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
        ApplyTokenRequest applyTokenRequest = new ApplyTokenRequest()
                .setResources(mqttConfigurer.getParenttopic())
                .setInstanceId(mqttConfigurer.getInstanceid())
                .setExpireTime(System.currentTimeMillis() + ExpireTime)
                .setActions(Actions);
        try {
            ApplyTokenResponse response = client.applyToken(applyTokenRequest);
            JSONObject json = new JSONObject(response.toMap());
            String data = String.valueOf(json.getJSONObject("body"));
            return ResultGenerator.genSuccessResult(data);
        }catch (Exception exception){
            return ResultGenerator.genFailResult(exception.getMessage());
        }
    }

    /**
     * 调用RevokeToken接口吊销Token
     *
     * @param Token 您需要吊销的Token
     * @return RequestId 公共参数
     * @throws Exception 异常
     */
    @ApiOperation(value = "吊销 Token")
    @RequestMapping(value = "/revoke",method = {RequestMethod.POST})
    public Result<Object> RevokeToken(@RequestParam String Token) throws Exception {
        MqttConfigurer mqttConfigurer = new MqttConfigurer();
        com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
        RevokeTokenRequest revokeTokenRequest = new RevokeTokenRequest()
                .setToken(Token)
                .setInstanceId(mqttConfigurer.getInstanceid());
        try {
            RevokeTokenResponse response = client.revokeToken(revokeTokenRequest);
            JSONObject json = new JSONObject(response.toMap());
            String data = String.valueOf(json.getJSONObject("body"));
            return ResultGenerator.genSuccessResult(data);
        }catch (Exception exception){
            return ResultGenerator.genFailResult(exception.getMessage());
        }
    }
}
